package com.example.springbootdemo.mylist.arrayList;

import com.example.springbootdemo.mylist.MyList;

import java.util.Arrays;

/**
 * @author cici
 */
public class MyArrayList implements MyList {

    private Object [] objectsList;

    private int size;

    private static final int DEFAULT_CAPACITY = 10;

    public MyArrayList(){
        this(DEFAULT_CAPACITY);
    }

    public MyArrayList(int initialCapacity){
        /*
         * 1.含参构造器
         * 2.要对传入的初始量的合法性进行检测
         * 3.通过新建数组实现
         */
        if(initialCapacity < 0){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        objectsList=new Object[initialCapacity];
    }

    @Override
    public boolean add(Object o) {
        checkSize();
        objectsList[size] = o;
        size = size + 1;
        return true;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        if (size == 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean contains(Object o) {
        for(Object object : objectsList){
            if (object.equals(o)){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean remove(int index) {
        /*
         * 1.下标合法性检测
         * 2.删除指定下标对象，并返回其值
         * 3.通过数组复制实现
         * 4.因为前移，数组最后一位要置为空
         */
        rangeCheck(index);
        int arrnums=size - index - 1;
        if(arrnums > 0){
            // 思路：从被删除的索引的下一位开始复制给新的当前数组索引的起始位置，长度为size - index - 1 --- 数学问题
            System.arraycopy(objectsList, index+1, objectsList,index, arrnums);
        }
        objectsList[--size]=null;
        return true;

    }

    @Override
    public boolean clear() {
        size = 0;
        return true;
    }

    @Override
    public Object get(int index) {
        return objectsList[index];
    }

    private void checkSize() {
        if(size == objectsList.length){
            Object[] newArray=new Object[size * 2 + 1];
            System.arraycopy(objectsList, 0, newArray, 0, objectsList.length);
            objectsList=newArray;
        }
    }

    private void rangeCheck(int index) {
        if(index<0||index>=size){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public String toString() {
        return "MyArrayList{" +
                "elementData=" + Arrays.toString(objectsList) +
                '}';
    }


}
